package com.library.service.impl;

import com.library.constant.IsReturnEnum;
import com.library.mapper.BookMapper;
import com.library.mapper.BorrowMapper;
import com.library.mapper.UserMapper;
import com.library.pojo.entity.LibraryBooks;
import com.library.pojo.entity.LibraryUsers;
import com.library.pojo.vo.BorrowVO;
import com.library.result.PageResult;
import com.library.service.BorrowService;
import com.library.pojo.dto.borrow.BorrowPageQueryDTO;
import com.library.pojo.entity.LibraryBorrow;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 借阅服务的实现类
 */
public class BorrowServiceImpl implements BorrowService {

    private final BookMapper bookMapper;
    private final BorrowMapper borrowMapper;
    private final UserMapper userMapper;
    private final SqlSessionFactory sqlSessionFactory;

    public BorrowServiceImpl() {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession(true);

            // 获取Mapper代理对象
            bookMapper = sqlSession.getMapper(BookMapper.class);
            borrowMapper = sqlSession.getMapper(BorrowMapper.class);
            userMapper = sqlSession.getMapper(UserMapper.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 分页查询借阅记录
     * @param borrowPageQueryDTO 分页参数（必填：pageNum/pageSize；可选：bookId/userId关键词）
     * @return PageResult<LibraryBorrow>：分页借阅记录列表
     */
    @Override
    public PageResult pageQuery(BorrowPageQueryDTO borrowPageQueryDTO) {
        // 开启事务
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            // 声明分页参数
            int pageNum = borrowPageQueryDTO.getPageNum();
            int pageSize = borrowPageQueryDTO.getPageSize();
            // 分页查询
            List<LibraryBorrow> borrows = borrowMapper.selectBorrowList((pageNum - 1) * pageSize, pageSize, borrowPageQueryDTO.getBookId(), borrowPageQueryDTO.getUserId());

            List<BorrowVO> borrowVOList = borrows.stream().map(borrow -> {
                // 查询图书信息
                LibraryBooks book = bookMapper.selectBookById(borrow.getBookId());
                // 查询用户信息
                LibraryUsers user = userMapper.selectById(borrow.getUserId());
                // 封装vo对象
                BorrowVO borrowVO = new BorrowVO();
                borrowVO.setBorrowId(borrow.getBorrowId());
                borrowVO.setUsername(user.getUsername());
                borrowVO.setName(book.getName());
                borrowVO.setIsReturn(borrow.getIsReturn());
                borrowVO.setBorrowTime(borrow.getBorrowTime());
                borrowVO.setReturnTime(borrow.getReturnTime());
                return borrowVO;
            }).toList();

            int borrowCount = borrowMapper.selectBorrowCount();

            // 封装结果
            PageResult pageResult = new PageResult();
            pageResult.setRecords(borrowVOList);
            pageResult.setTotal(borrowCount);
            return pageResult;
        } catch (Exception e) {
//            System.out.println("查询借阅记录失败");
            return null;
        }
    }

    /**
     * 还书
     *
     * @param borrowId 借阅编号
     */
    @Override
    public int revert(Integer borrowId) {
        // 开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            // 查找借阅记录
            LibraryBorrow libraryBorrow = borrowMapper.selectBorrowByBorrowId(borrowId);
            // 判断借阅记录是否存在
            if (libraryBorrow == null) {
//                System.out.println("借阅记录不存在");
                return 0;
            }
            // 判断图书是否已归还
            if (IsReturnEnum.RETURN.getCode().equals(libraryBorrow.getIsReturn())) {
//                System.out.println("该图书已归还");
                return 0;
            }
            // 获取图书信息
            LibraryBooks book = bookMapper.selectBookById(libraryBorrow.getBookId());
            // 判断图书信息是否存在
            if (book == null) {
//                System.out.println("没有找到该图书");
                return 0;
            }
            // 获取用户信息
            LibraryUsers user = userMapper.selectById(libraryBorrow.getUserId());
            if (user == null) {
                System.out.println("没有找到该用户");
                return 0;
            }
            // 更新借阅记录
            libraryBorrow.setIsReturn(IsReturnEnum.RETURN.getCode());
            libraryBorrow.setReturnTime(LocalDateTime.now());
            int updateBorrowResult = borrowMapper.updateBorrow(libraryBorrow);
            if (updateBorrowResult == 0) {
                sqlSession.rollback();
                return 0;
            }
            // 更新图书库存量
            book.setStock(book.getLoan() + 1);
            int updateBookResult = bookMapper.updateBook(book);
            if (updateBookResult == 0) {
                sqlSession.rollback();
                return 0;
            }
            sqlSession.commit();
            return 1;
        } catch (Exception e) {
            sqlSession.rollback();
            return 0;
        } finally {
            sqlSession.close();
        }
    }
}
